<?php
class Category extends Controller
{
	private $tbl = 'tbl_publication_category';
 	function Category()
	{
		parent::Controller();	
	}
	
	function index()
	{
		
		$data['categories']	= $this->general_db_model->getAll($this->tbl, 'code', 'parent_id = 0');
		$data['page_title']	= 'Manage Thematic Areas';
		$data['page'] = 'category_list_v';
		$this->load->view('main', $data);	
	}
	
	function add()
	{
		if($this->input->post('submit_category'))
		{
			$this->add_edit();	
		}
		$data['categories'] = $this->general_db_model->getAll($this->tbl, 'category_name', 'parent_id = 0');
		//debug_array($data);
		$data['page_title']	 = 'Add Thematic Area';
		$data['page'] = 'category_add_v';
		$this->load->view('main', $data);
	}
	
	function edit($id)
	{
		if($this->input->post('submit_category'))
		{
			$this->add_edit($id);	
		}
		
		$data['categories'] = $this->general_db_model->getAll($this->tbl, 'category_name', 'parent_id = 0');
		$data['_cat'] = $this->general_db_model->getById($this->tbl, 'id', $id);
		$data['page_title']	 = 'Update Thematic Area';
		$data['page'] = 'category_add_v';
		$this->load->view('main', $data);	
	}
	
	function add_edit($id = NULL)
	{
            //debug_array($_POST);exit;
		 $parent_id = $data['parent_id'] = $this->input->post('parent_id');
		 $data['category_name'] = $this->input->post('category_name');
		 $data['code']= $this->input->post('code');//generate_category_code($parent_id);
                 if($id)
		 {
		 	$this->general_db_model->update($this->tbl, $data, 'id = '.$id);
			$this->session->set_flashdata('success_message', 'Thematic Area - '.$data['category_name'].' :: Successfully updated.');
		 }
		 else
		 {
		 	$this->general_db_model->insert($this->tbl, $data);
		 	$this->session->set_flashdata('success_message', 'Thematic Area - '.$data['category_name'].' :: Successfully added.');
		 }
		 
		 redirect(current_url());
	}
	
	function delete_category()
	{
	 	$cat_id = $this->input->post('c_id');
		$isParent = $this->input->post('p_cat');
		
		$this->general_db_model->delete($this->tbl, 'id = '.$cat_id);
		
		if($isParent)
			$this->general_db_model->delete($this->tbl, 'parent_id = '.$cat_id);
	}

        function ajax_generate_code(){
            $parent_id = $this->input->post('parent_id');
            $category_code = generate_category_code($parent_id);
            echo $category_code;exit;
        }
}

?>